/**
 * 授权检查中间件
 *
 * 放行白名单中的请求地址，非白名单中的地址请求校验身份，
 * 校验通过后放行。
 */
import { ssrMiddleware } from 'quasar/wrappers'
import jwt from 'jsonwebtoken';
import * as tools from 'src-ssr/util/common';

global.privateKey = 'MDY20240826';
global.oauthState = 'mdyoauth';

// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/developing-ssr/ssr-middlewares
export default ssrMiddleware(async ({ app/* , resolveUrlPath, publicPath, render */ }) => {
  // something to do with the server "app"
  const excludeVerify = (path) => {
    // console.log('*****' + path + '*****')
    const whiteList = ['/', '/mLogin', '/tLogin',
      '/checkToken',
      '/c/system/getSiteConfig',
      '/c/wechat/getAuthorizeURL'];
    const whiteListLevel3 = []; // ['/c2/manager/login'];
    const whiteListLevel2 = ['/c/login', '/c/share', '/c/shop'];
    const whiteListLevel1 = ['main', 'uploads', 'public', 'share', 'cockpit', 'shop'];
    const staticResource = ['txt', 'jpg', 'png', 'gif', 'jpeg', 'mp3'];

    if (whiteList.includes(path)) { // 白名单完全匹配
      return true;
    } else {
      const pathArr = path.split('/');
      if (pathArr.length > 3 && whiteListLevel3.includes(`/${pathArr[1]}/${pathArr[2]}/${pathArr[3]}`)) { // 路径1，2，3级相同同的白名单
        return true;
      } else if (pathArr.length > 2 && whiteListLevel2.includes(`/${pathArr[1]}/${pathArr[2]}`)) { // 路径1，2级相同同的白名单
        return true;
      } else if (pathArr.length > 2 && whiteListLevel1.includes(pathArr[1])) { // /main/* /process/*
        return true;
      } else if (pathArr.length === 2 && pathArr[1].indexOf('.') >= 0 && staticResource.includes(pathArr[1].split('.')[1].toLowerCase())) { // 静态资源
        return true;
      } else {
        return false;
      }
    }
  };

  /**
  * 身份验证
  */
  app.use('*', async (req, res, next) => {
    if (!global.domainHost) {
      global.domainHost = await tools.globalHost(req);
    }

    if (!excludeVerify(req.params['0'])) {
      const token = req.get('Authorization') ? req.get('Authorization').split(' ') : [];
      if (token.length < 2) {
        res.status(401).send('Unauthorized');
      } else {
        jwt.verify(token[1], global.privateKey, (err, decoded) => {
          // console.log(token[1], err, decoded);
          if (err) { // 过期
            res.status(401).send(err);
          } else {
            // 更新jwt过期时间
            const { tid, id, nickname } = decoded;
            const token = 'Bearer ' + jwt.sign({ tid, id, nickname }, global.privateKey, { expiresIn: 7 * 24 * 60 * 60 });
            res.header('Authorization', token);
            res.header('reauthuid', id); // 当前jwt的所属用户，用了apache的反向代理时，会把上次登录的jwt发送回去，这个用于鉴别

            // console.log(moment().format('YYYY/MM/DD HH:mm:ss'), nickname, req.originalUrl, ip, req.get('x-forwarded-for'));
            next();
          }
        });
      }
    } else {
      // 删除UTF-8编码 防止出现status 415的错误
      if (req.headers && req.headers['content-encoding'] && req.headers['content-encoding'].indexOf('UTF-8') > -1) {
        delete req.headers['content-encoding'];
      }
      next();
    }
  });
});
